﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Inkubator.Wizard.Model.Xml;
using System.Web.UI.WebControls;

namespace SerializeResults
{
    public class SerializeResults : IAction
    {

        public void prepare(object[] arguments) { }

        public bool evaluate(object[] arguments) { return false; }

        public void execute(object[] arguments)
        {
            List<object> list = arguments.ToList<object>();

            WizardResult wizard = this.convertList(list);

            XmlOperations xml = new XmlOperations();
            xml.serialize(wizard, "C:\\diego\\programacion\\wizardResults.xml");
        }

        private WizardResult convertList(List<object> arguments)
        {
            WizardResult wizardResults = new WizardResult();

            foreach (object[] step in arguments)
            {
                StepResult stepResults = new StepResult();
                object[] ids = (object[]) step[0];
                object[] values = (object[])step[1];

                for (int i = 0; i < ids.Length; i++)
                {
                    Result result = new Result();
                    result.id = (string) ids[i];
                    if (values[i].GetType() == typeof(DateTime))
                    {
                        result.value = ((DateTime)values[i]).ToString();
                    }
                    else if(values[i].GetType() == typeof(System.Web.UI.WebControls.TableRowCollection))
                    {
                        TableRowCollection rows = ((TableRowCollection)values[i]);
                        Table table = new Table();

                        for (int j = 0; j < rows.Count; j++)
                        {
                            TableRow row = rows[j];
                            Row rowTable = new Row();

                            for (int q = 0; q < row.Cells.Count; q++)
                            {
                                TableCell cell = row.Cells[q];
                                TextBox text = (TextBox)cell.Controls[0];

                                rowTable.addItem(text.Text);
                            }

                            table.addRow(rowTable);
                        }

                        result.setTable(table);
                    }
                    else
                    {
                        result.value = (string)values[i];
                    }
                    
                    stepResults.addResult(result);
                }

                wizardResults.addStep(stepResults);
            }

            return wizardResults;
        }

    }
}
